package org.example.service;


import jakarta.annotation.Resource;
import org.example.entity.LoginDTO;
import org.example.entity.ResponseModel;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


@Service
public class LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    public ResponseModel<String> checkLogin(LoginDTO dto) {
        // 获取用户名密码
        String username = dto.getUsername();
        String password = dto.getPassword();
        // 尝试创建一个待认证的对象
        UsernamePasswordAuthenticationToken authRequest =
                new UsernamePasswordAuthenticationToken(username, password);
        // 发起认证
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(authRequest);
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        // 判断是否真正成功
        if (authentication != null && authentication.isAuthenticated()) {
            // 认证成功后放入安全上下文中供后续过滤器使用（重要）
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return ResponseModel.authSuccess("认证成功");
        } else {
            return ResponseModel.authFailure("认证失败");
        }
    }


}
